﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Windows;
using StockModel;
using Utils;
using Utils.Wpf;

namespace StockAnalyst2.Plugins.Visualization.Historical
{
	internal class ResultViewerVM : ViewModelBase, IDisposable
	{
		#region Attributes

		private bool _isVisible;
		private readonly ObservableCollection2<Operation> _result;

		#endregion

		#region Properties

		public bool IsVisible
		{
			get
			{
				return _isVisible;
			}
			set
			{
				if (_isVisible != value)
				{
					_isVisible = value;
					base.OnPropertyChanged("IsVisible");
				}
			}
		}

		public SummaryViewerVM SummaryViewerVM { get; private set; }
		public ResultChartVM ResultChartVM { get; private set; }
		public DetailViewerVM DetailViewerVM { get; private set; }
		public CustomDataViewerVM CustomDataViewerVM { get; private set; }

		#endregion

		#region Public Methods

		public ResultViewerVM(ExecutionResultStatistics statistics, ObservableCollection2<Operation> result, ObservableCollection<FrameworkElement> images)
		{
			this.SummaryViewerVM = new SummaryViewerVM(statistics);
			this.ResultChartVM = new ResultChartVM(statistics);
			this.DetailViewerVM = new DetailViewerVM(result, statistics);
			this.CustomDataViewerVM = new CustomDataViewerVM(images);

			_result = result;
			_result.CollectionChanged += Result_CollectionChanged; // Disposed
		}

		#endregion

		#region Event Handlers

		private void Result_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Add)
			{
				this.IsVisible = true;
			}
			else if (e.Action == NotifyCollectionChangedAction.Reset)
			{
				this.IsVisible = false;
			}
			else
			{
				Debug.WriteLine("Unexpected action received at the ResultViewerVM: " + e.Action.ToString());
			}
		}

		#endregion

		#region IDisposable

		protected bool Disposed { get; private set; }

		private void Dispose(bool disposing)
		{
			if (!this.Disposed)
			{
				this.InternalDispose(disposing);
			}

			this.Disposed = true;
		}

		protected virtual void InternalDispose(bool disposing)
		{
			if (disposing)
			{
				_result.CollectionChanged -= Result_CollectionChanged;

				this.DetailViewerVM.Dispose();
				this.ResultChartVM.Dispose();
				this.SummaryViewerVM.Dispose();
			}

			// Dispose here only unmanaged objects 
			// Don’t use managed objects here because maybe 
			// they have been finalized already
		}

		public void Dispose()
		{
			this.Dispose(true);
			GC.SuppressFinalize(this);
		}

		~ResultViewerVM()
		{
			this.Dispose(false);
		}

		#endregion

	}
}
